package com.jarvis.pzz.modules.sellshop;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Build;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;
import com.jarvis.pzz.R;
import com.jarvis.pzz.common.BaseActivity;
import com.jarvis.pzz.common.FileResponseData;
import com.jarvis.pzz.common.ResponseData;
import com.jarvis.pzz.models.FileModel;
import com.jarvis.pzz.modules.completed.ReleaseCompletedActivity;
import com.jarvis.pzz.seervers.FileRequestService;
import com.jarvis.pzz.seervers.RequestService;
import com.jarvis.pzz.util.AddressManager;
import com.jarvis.pzz.util.SharePreferenceKey;
import com.jarvis.pzz.util.net.RequestApi;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import me.iwf.photopicker.PhotoPicker;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.functions.Action1;

public class SellShopActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.rel_left)
    RelativeLayout rel_left;
    @BindView(R.id.lin_title)
    RelativeLayout lin_title;
    @BindView(R.id.et_sell_mj)
    EditText et_sell_mj;
    @BindView(R.id.et_sell_dz)
    EditText et_sell_dz;
    @BindView(R.id.et_sell_dh)
    EditText et_sell_dh;
    @BindView(R.id.et_sell_zb)
    TextView et_sell_zb;
    @BindView(R.id.ll_sell_dw)
    LinearLayout ll_sell_dw;
    @BindView(R.id.tv_sell_publish)
    TextView tv_sell_publish;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_notice)
    TextView tv_notice;


    @BindView(R.id.img_sell1)
    ImageView img_sell1;
    @BindView(R.id.img_sell2)
    ImageView img_sell2;
    @BindView(R.id.img_sell3)
    ImageView img_sell3;


    private RequestService services;
    private FileRequestService file_services;
    private int to_sell = 1;
    private FileModel model_11;
    private FileModel model_22;
    private FileModel model_33;

    private String photo_path_1 = "";
    private String photo_path_2 = "";
    private String photo_path_3 = "";

    private int type = -1;
    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    @Override
    public int getLayoutId() {
        return R.layout.activity_sell_shop;
    }

    @Override
    public void initData() {
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();

    }

    @Override
    public void initView() {
        Intent _intent = getIntent();
        if (_intent != null) {
            to_sell = _intent.getIntExtra("TO_SELL", 0);
            if (to_sell == 0) {
                //转铺
                tv_title.setText(R.string.shop_to_title);
                tv_notice.setVisibility(View.VISIBLE);
            } else if (to_sell == 1) {
                //卖铺
                tv_title.setText(R.string.shop_sell_title);
                tv_notice.setVisibility(View.GONE);
            }

        }
        services = RequestApi.create(RequestService.class);
        final String url = AddressManager.getFileHost();
        file_services = RequestApi.create(FileRequestService.class,url);
        setBar();
        setListener();


    }

    /**
     * 设置监听事件
     */
    public void setListener() {
        rel_left.setOnClickListener(this);
        ll_sell_dw.setOnClickListener(this);
        img_sell1.setOnClickListener(this);
        img_sell2.setOnClickListener(this);
        img_sell3.setOnClickListener(this);
        tv_sell_publish.setOnClickListener(this);

    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            android.support.v7.app.AlertDialog.Builder dialogBuilder = new android.support.v7.app.AlertDialog.Builder(this)
                    .setTitle("铺找找温馨提示")
                    .setMessage("老板 您不想转店了吗？")
                    .setNegativeButton("狠心离开", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .setPositiveButton("继续留下", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

            dialogBuilder.create().show();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rel_left:
                android.support.v7.app.AlertDialog.Builder dialogBuilder = new android.support.v7.app.AlertDialog.Builder(this)
                        .setTitle("铺找找温馨提示")
                        .setMessage("老板 您不想转店了吗？")
                        .setNegativeButton("狠心离开", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        })
                        .setPositiveButton("继续留下", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

                dialogBuilder.create().show();
                break;
            case R.id.ll_sell_dw:
                mLocClient.start();
                //定位
                break;
            case R.id.tv_sell_publish:
                //确定发布
                if (getVerification()) {
                    getsaveShop();
                }
                break;
            case R.id.img_sell1:
                //左
                type = 1;
                RxPermissions.getInstance(this)
                        .request(Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.CAMERA)
                        .subscribe(new Action1<Boolean>() {
                            @Override
                            public void call(Boolean aBoolean) {
                                if (aBoolean) {
                                    takePhoto(1);
                                } else {
                                    showTextToast("请选择允许使用权限");
                                }
                            }
                        });
                break;
            case R.id.img_sell2:
                //正
                type = 2;
                RxPermissions.getInstance(this)
                        .request(Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.CAMERA)
                        .subscribe(new Action1<Boolean>() {
                            @Override
                            public void call(Boolean aBoolean) {
                                if (aBoolean) {
                                    takePhoto(2);
                                } else {
                                    showTextToast("请选择允许使用权限");
                                }
                            }
                        });
                break;

            case R.id.img_sell3:
                //右
                type = 3;
                RxPermissions.getInstance(this)
                        .request(Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.CAMERA)
                        .subscribe(new Action1<Boolean>() {
                            @Override
                            public void call(Boolean aBoolean) {
                                if (aBoolean) {
                                    takePhoto(3);
                                } else {
                                    showTextToast("请选择允许使用权限");
                                }
                            }
                        });
                break;
        }
    }


    private boolean getVerification() {

        if(model_22==null){
            showTextToast("至少上传一张店铺正面照");
            return false;
        }

        if (TextUtils.isEmpty(et_sell_mj.getText().toString())) {
            showTextToast("请输入店铺面积");
            return false;
        }
        if (TextUtils.isEmpty(et_sell_dz.getText().toString())) {
            showTextToast("请输入详细地址");
            return false;
        }

        if (!TextUtils.isEmpty(et_sell_dh.getText().toString())) {
            if (!isPhoneNumber(et_sell_dh.getText().toString())) {
                showTextToast("请输入正确联系电话");
                return false;
            }
        }


        if (TextUtils.isEmpty(et_sell_zb.getText().toString())) {
            showTextToast("请输入定位坐标");
            return false;
        }


        return true;
    }


    /**
     * 判断手机号是否符合规范
     *
     * @param phoneNo 输入的手机号
     * @return
     */
    public static boolean isPhoneNumber(String phoneNo) {
        if (TextUtils.isEmpty(phoneNo)) {
            return false;
        }
        if (phoneNo.length() == 11) {
            for (int i = 0; i < 11; i++) {
                if (!PhoneNumberUtils.isISODigit(phoneNo.charAt(i))) {
                    return false;
                }
            }
            Pattern p = Pattern.compile("^((13[^4,\\D])" + "|(134[^9,\\D])" +
                    "|(14[5,7])" +
                    "|(15[^4,\\D])" +
                    "|(17[3,6-8])" +
                    "|(18[0-9]))\\d{8}$");
            Matcher m = p.matcher(phoneNo);
            return m.matches();
        }
        return false;
    }

    public void takePhoto(int code) {
        PhotoPicker.builder()
                .setPhotoCount(1)
                .setShowCamera(true)
                .setShowGif(true)
                .setPreviewEnabled(false)
                .start(this, code);
    }

    private void setBar() {
        lin_title.setVisibility(View.VISIBLE);
        lin_title.getBackground().setAlpha(255);
        int statusBarHeight1 = -1;
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
        }
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(lin_title.getLayoutParams());
        lp.setMargins(0, statusBarHeight1, 0, 0);
        lin_title.setLayoutParams(lp);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 1) {
            if (data != null) {
                final ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                photo_path_1 = photos.get(0);
                upImage();
            }
        } else if (resultCode == RESULT_OK && requestCode == 2) {
            if (data != null) {
                final ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                photo_path_2 = photos.get(0);
                upImage();
            }
        } else if (resultCode == RESULT_OK && requestCode == 3) {
            if (data != null) {
                final ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                photo_path_3 = photos.get(0);
                upImage();
            }
        }
    }

    /**
     * 判断摄像头是否被禁
     */
    public static boolean isCamera() {
        boolean canUse = true;
        Camera camera = null;
        try {
            camera = Camera.open();
        } catch (Exception var3) {
            canUse = false;
        }
        if (canUse) {
            camera.release();
            camera = null;
        }
        return canUse;
    }

    /**
     * 摄像头被禁提示
     *
     * @param context
     */
    public static void cameraTipDialog(Context context) {
        AlertDialog.Builder builder = getAlertDialogBuilder(context);
        builder.setTitle("提示");
        builder.setMessage("请允许使用相机！设置步骤：安全中心-权限管理-按应用管理-铺找找-相机-允许");
        builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.show();
    }

    /**
     * @param context
     * @return
     */
    public static AlertDialog.Builder getAlertDialogBuilder(Context context) {
        AlertDialog.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Light_Dialog_Alert);
        } else {
            builder = new AlertDialog.Builder(context);
        }
        return builder;
    }

    private void upImage() {
        showDialog("loading");
        String path = "";
        if (type == 1) {
            path = photo_path_1;
        } else if (type == 2) {
            path = photo_path_2;
        } else {
            path = photo_path_3;
        }

        File file = new File(path);//filePath 图片地址
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)//表单类型
                .addFormDataPart("folderName", "shop");//ParamKey.TOKEN 自定义参数key常量类，即参数名
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        builder.addFormDataPart("files", file.getName(), imageBody);//imgfile 后台接收图片流的参数名
        List<MultipartBody.Part> parts = builder.build().parts();
        Call<FileResponseData<List<FileModel>>> call = file_services.uploadImage(parts);
        call.enqueue(new Callback<FileResponseData<List<FileModel>>>() {
            @Override
            public void onResponse(Call<FileResponseData<List<FileModel>>> call, Response<FileResponseData<List<FileModel>>> response) {
                disMiss();
                if (response.body() != null) {
                    int statusCode = response.body().getCode();
                    if (statusCode == 200) {
                        if (type == 1) {
                            model_11 = response.body().getResult().get(0);
                            Glide.with(mActivity)
                                    .load(photo_path_1)
                                    .centerCrop()
                                    .into(img_sell1);
                        } else if (type == 2) {
                            model_22 = response.body().getResult().get(0);
                            Glide.with(mActivity)
                                    .load(photo_path_2)
                                    .centerCrop()
                                    .into(img_sell2);
                        } else {
                            model_33 = response.body().getResult().get(0);
                            Glide.with(mActivity)
                                    .load(photo_path_3)
                                    .centerCrop()
                                    .into(img_sell3);
                        }
                    } else {
                        showTextToast(response.body().getDesc());
                    }
                } else {
                    showTextToast("请求失败");
                }
            }

            @Override
            public void onFailure(Call<FileResponseData<List<FileModel>>> call, Throwable t) {
                disMiss();
                showTextToast(RequestApi.detailError(t));
            }
        });
    }

    //12 发布求租信息
    private void getsaveShop() {
        String sell_mj = et_sell_mj.getText().toString();
        String sell_dz = et_sell_dz.getText().toString();
        String sell_dh = et_sell_dh.getText().toString();
        String sell_zb = et_sell_zb.getText().toString();

        String path1="";
        String path2="";
        String path3="";
        if(model_11!=null){
            path1=model_11.getFileId()+"$"+model_11.getFilePath();
        }
        if(model_22!=null){
            path2=model_22.getFileId()+"$"+model_22.getFilePath();
        }
        if(model_33!=null){
            path3=model_33.getFileId()+"$"+model_33.getFilePath();
        }



        Call<ResponseData> responseDataCall = services.getsaveShop(String.valueOf(to_sell), path1,
                path2, path3, sell_mj, sell_dz, sell_dh, sell_zb);
        responseDataCall.enqueue(new Callback<ResponseData>() {
            @Override
            public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {
                if (response.body() != null) {
                    int total_count = response.body().getTotalcount();
                    int resultCode = response.body().getResultCode();
                    if (resultCode == 200) {
                        //成功
                        startActivity(new Intent(mActivity, ReleaseCompletedActivity.class));
                        SharePreferenceKey.SHOPMEASUREAREA = et_sell_mj.getText().toString();//面积
                        finish();
                    } else {
                        showTextToast(response.body().getMessage());
                    }
                } else {
                    showTextToast("请求失败");
                }
            }

            @Override
            public void onFailure(Call<ResponseData> call, Throwable t) {
                showTextToast(RequestApi.detailError(t));
            }
        });

    }
    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        super.onDestroy();
    }
    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null ) {
                return;
            }
            et_sell_zb.setText(location.getLatitude()+","+ location.getLongitude());
//            Toast.makeText(SellShopActivity.this, "city:" + location.getCity()+ "  District:" + location.getDistrict()+"  latitude:" + location.getLatitude()
//                    + " longitude:" + location.getLongitude() + "---", Toast.LENGTH_LONG)
//                    .show();
            if (mLocClient.isStarted()) {
                // 获得位置之后停止定位
                mLocClient.stop();
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }
}
